package com.znjc.iot.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Timer;
import java.util.TimerTask;

/**
 * WebSocket客户端配置类
 */
@Configuration
@Slf4j
public class WebSocketClientConfig {

    @Autowired
    private Environment env;

    /**
     * socket连接地址
     */
    @Value("${znjc.socket.url}")
    private String webSocketUri;

    @Value("${znjc.clientId}")
    private String clientId;

    /**
     * 注入Socket客户端
     *
     * @return
     */
    @Bean
    public CustomizedWebSocketClient initWebSocketClient() {
        URI uri = null;
        try {
            uri = new URI(webSocketUri+clientId);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        CustomizedWebSocketClient webSocketClient = new CustomizedWebSocketClient(uri);
        //启动时创建客户端连接
        webSocketClient.connect();
        Timer t = new Timer();
        t.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                if(webSocketClient.isClosed()){
                    log.error("断线重连");
                    webSocketClient.reconnect();
                }
            }
        },1000,10000);
        return webSocketClient;
    }

}

